<?php
namespace Cyfy;

/**
 * Translating classes.
 *
 * Abstract class used for translating other classes, which are derived from it.
 *
 * @category cyfy
 * @author Dandelion <dandelion8888@gmail.com>
 * @version 0.1
 */ 
abstract class Translatable
{
    /**
     * Array, which contains texts in various languages.
     * Example:
     * <code>
     * $lang = array(
     *      'ClassName' => array(
     *          'en' => array(
     *              10 => 'Some text'
     *              20 => 'Another text'
     *              21 => 'Another text, connected somehow to text 20 and contains one variable part %s'
     *          );
     *      );
     * );
     * </code>
     * @var
     */
    static protected $langData = array();
    
    /**
     * Module name in traslation. Must be stored in array('ClassName'=>'name'), beacuse of PHP problems with inheriting
     * @var array
     */
    static protected $nameData = array();
 
    /**
     * Sets module name.
     * @param string Module name.
     */
    static function setName($name)
    {
        $calledClass = get_called_class();
        self :: $nameData[$calledClass] = $name;
    }
    
    /**
     * Gets module name.
     * @return string
     */
    static function getName()
    {
        $calledClass = get_called_class();
        return self :: $nameData[$calledClass];
    }
    
    /**
     * Fills language array.
     *
     * @see self :: $lang
     * @param string Two letter code of the language.
     * @param array Contents of the language.
     */
    static public function addLanguageData($language, $contents)
    {
        self :: $langData[get_called_class()][$language] = $contents;
    }
    
    /**
     * Translates a code to a message in current language.
     *
     * @param int           Code of the message.
     * @param mixed         ARRAY with parts to be inserted into the message or FALSE when no parts to translate.
     * @return string       Transformed message.
     */
    static public function t($code, $parts = false)
    {
        $cls = get_called_class();
        $text = self :: $langData[$cls][\Cyfy\Language :: getActive()][$code];
        // if no text, try to reload
        if(!$text){
            $filename = classToPath($cls);   
            loadLanguageFile($cls, $filename);
            $text = self :: $langData[$cls][\Cyfy\Language :: getActive()][$code];
        }
        
        // if no text show code
        if(!$text){
           return "Missing text #{$code} in " . $cls;
        }
        
        // if some parts to be translated
        if($parts)
        {
            return vsprintf($text, $parts);
        }
        
        // plain text
        return $text;       
    }
}
